﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ServiceStack.Redis;

namespace RedisTool
{
    public partial class ServerConfig : Form
    {
        public ServerConfig()
        {
            InitializeComponent();
        }

        private void ServerConfig_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(this.DialogResult==DialogResult.OK 
                && (String.IsNullOrEmpty(tb_name.Text)||String.IsNullOrEmpty(tb_host.Text)))
            {
                MessageBox.Show(this,"请输入名称和主机地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel=true;
            }
        }

        private void b_test_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(tb_name.Text) || String.IsNullOrEmpty(tb_host.Text))
            {
                MessageBox.Show(this, "请输入名称和主机地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                RedisNativeClient server=null;
                try
                {
                    string password = tb_password.Text;
                    if (tb_password.UseSystemPasswordChar && !String.IsNullOrEmpty(password))
                        password = AESKit.Decrypt(password, MainForm.aesKey);
                    server = new RedisNativeClient(tb_host.Text, (int)tb_port.Value, password);
                    if (server.Ping())
                        MessageBox.Show(this, "测试通过！");
                    else
                        MessageBox.Show(this, "服务器测试出错！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch(Exception ee)
                {
                    MessageBox.Show(this, "连接错误:" + ee.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (server != null) server.Dispose(); 
                }
            }
        }

        private void tb_password_TextChanged(object sender, EventArgs e)
        {

        }

        private void tb_password_Enter(object sender, EventArgs e)
        {
            if (tb_password.UseSystemPasswordChar)
            {
                tb_password.UseSystemPasswordChar = false;
                tb_password.Text = "";
            }
        }
    }
}
